package com.snow.useviewdemo.function2.notice

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.RingtoneManager
import android.os.Build
import android.os.Bundle
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.Person
import androidx.core.graphics.drawable.IconCompat
import com.bumptech.glide.Glide
import com.snow.common.tool.utils.ToastUtils
import com.snow.useviewdemo.R
import com.snow.useviewdemo.base.BaseKotlinActivity
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_resident_notice_test.*
import java.util.concurrent.ExecutionException


/**
 * Created by zhaoyingtao
 * Date: 2020/10/13
 * Describe:测试通知
 * 注意点：
 * 如果您的应用发出 4 条或更多条通知且未指定通知组，那么在 Android 7.0 及更高版本上，系统会自动将这些通知分为一组。
 * 自定义组收起状态点击子通知不能展开，所以对相关通知不设置group，使系统自动合组
 */
class ResidentNoticeTestActivity : BaseKotlinActivity() {
    override fun getLayoutId(): Int {
        return R.layout.activity_resident_notice_test
    }

    override fun setViewData(savedInstanceState: Bundle?) {
        btn.setOnClickListener {
            Observable.unsafeCreate<Bitmap> { observer ->
                var imgBitMap = getImgBitMap()
                if (imgBitMap != null) {
                    observer.onNext(imgBitMap)
                } else {
                    observer.onError(Exception("imgBitMap == null"))
                }
            }.subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe {
                    var notificationBuilder = createDefaultNotifyBuilder()
//                        .setLargeIcon(it)
                        .setContentTitle("BigTextStyle 通知")
                        .setContentText("ContentText")
                        .setStyle(
                            NotificationCompat.BigTextStyle()
                                .setBigContentTitle("BigContentTitle")
                                .bigText("bigText")
//                                .setSummaryText("SummaryText")
                        );

                    NotificationManagerCompat.from(this)
                        .notify(getRandomNotifyId(), notificationBuilder.build())
                }
        }
        btn1111.setOnClickListener {
            var imgBitMap = getImgBitMap()
            var notificationBuilder = createDefaultNotifyBuilder()
                .setLargeIcon(imgBitMap)
                .setContentTitle("InboxStyle 通知")
                .setContentText("ContentText")
                .setStyle(
                    NotificationCompat.InboxStyle()
                        .setBigContentTitle("BigContentTitle")
                        .setSummaryText("SummaryText")
                )
            NotificationManagerCompat.from(this)
                .notify(getRandomNotifyId(), notificationBuilder.build())
        }
        btn222.setOnClickListener {
            Observable.unsafeCreate<Bitmap> { observer ->
                var imgBitMap = getImgBitMap()
                if (imgBitMap != null) {
                    observer.onNext(imgBitMap)
                } else {
                    observer.onError(Exception("imgBitMap == null"))
                }
            }.subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe {
                    var notificationBuilder = createDefaultNotifyBuilder()
                        .setLargeIcon(it)
                        .setContentTitle("BigPictureStyle 通知")
                        .setContentText("ContentText")
                        .setStyle(
                            NotificationCompat.BigPictureStyle()
                                .bigPicture(it)
                                .setBigContentTitle("BigContentTitle")
//                                .setSummaryText("SummaryText")
                                .bigLargeIcon(null)
                        )

                    NotificationManagerCompat.from(this)
                        .notify(getRandomNotifyId(), notificationBuilder.build())
                }
        }
        btn333.setOnClickListener {
            Observable.unsafeCreate<Bitmap> { observer ->
                var imgBitMap = getImgBitMap()
                if (imgBitMap != null) {
                    observer.onNext(imgBitMap)
                } else {
                    observer.onError(Exception("imgBitMap == null"))
                }
            }.subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe {
                    val person = Person.Builder()
                        .setName("personName")
                        .setIcon(IconCompat.createWithBitmap(it))
                        .build()
                    var notificationBuilder = createDefaultNotifyBuilder()
                        .setLargeIcon(it)
                        .setContentTitle("MessagingStyle 通知")
                        .setContentText("ContentText")
                        .setStyle(
                            NotificationCompat.MessagingStyle(person)
                                .setConversationTitle("Team lunch")
                                .addMessage("What's up?", System.currentTimeMillis(), person)
                                .addMessage("Not much", System.currentTimeMillis(), person)
                        )

                    NotificationManagerCompat.from(this)
                        .notify(getRandomNotifyId(), notificationBuilder.build())
                }
        }
        btn444.setOnClickListener {
            val customView = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                RemoteViews(
                    this.packageName,
                    R.layout.layout_custom_notification_android_s
                )
            } else {
                RemoteViews(
                    this.packageName,
                    R.layout.layout_custom_notification
                )
            }
            val bitCustomView = RemoteViews(
                this.packageName,
                R.layout.layout_custom_notification_big
            )
            var notificationBuilder = createDefaultNotifyBuilder()
//                .setLargeIcon(imgBitMap)
//                .setContentTitle("ContentTitle")
//                .setContentText("ContentText")
//                .setStyle(NotificationCompat.DecoratedCustomViewStyle())
                .setCustomContentView(customView)
                .setCustomBigContentView(bitCustomView);

            NotificationManagerCompat.from(this)
                .notify(getRandomNotifyId(), notificationBuilder.build())
        }
        btn555.setOnClickListener {

        }
    }

    private fun getRandomNotifyId(): Int {
        var random = Math.random()
        return (random * 10000).toInt()
    }

    private fun getImgBitMap(): Bitmap? {
        var bitmap: Bitmap? = null
        try {
            val imgUrl =
                "https://scpic.chinaz.net/files/default/imgs/2022-10-05/4a3e40f0099e7da2.jpg"
            bitmap = Glide.with(this)
                .asBitmap()
                .load(imgUrl)
                .submit().get()//必须在子线程中处理
        } catch (e: ExecutionException) {
            e.printStackTrace()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
            bitmap = BitmapFactory.decodeResource(resources, R.mipmap.chat_tool_audio)
        }
        return bitmap
    }

    private fun createNotifyChannelId(context: Context): String {
        var channelId = "default_channel"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val appName = context.resources.getString(R.string.app_name)
            val descriptionText = "channel_description"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            var channel = NotificationChannel(channelId, appName, importance).apply {
                description = descriptionText
            }
            NotificationManagerCompat.from(context).createNotificationChannel(channel)
        }
        return channelId
    }

    private fun createDefaultNotifyBuilder(): NotificationCompat.Builder {
        var channelId = createNotifyChannelId(this)
        return NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.icon_clock_in_complete)//小图标，必须设置
//            .setGroup(getRandomNotifyId().toString())
//            .setGroupSummary(true)
//            .setOngoing(true)//ture，设置他为一个正在进行的通知。他们通常是用来做常驻设置
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setDefaults(NotificationCompat.DEFAULT_ALL)//设置默认的灯光，提示音和振动，可选值：DEFAULT_ALL，DEFAULT_SOUND，DEFAULT_VIBRATE，DEFAULT_LIGHTS
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)//5.0以后添加
            .setWhen(System.currentTimeMillis())        //设置通知上显示的时间
            .setShowWhen(true)                          //通知是否显示时间
            .setPriority(NotificationCompat.PRIORITY_MAX) //设置等级，可选值有PRIORITY_MIN（-2），PRIORITY_LOW（-1），PRIORITY_DEFAULT（0），PRIORITY_HIGH（1），PRIORITY_MAX（2），默认为0
            .setAutoCancel(true)                          //是否自动消失，true表示响应点击之后自动消失。

    }
}